package com.small.act.discount;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.small.R;
import com.small.act.MsgActivity;
import com.small.act.old.DzHomeActivity_old;
import com.small.adapter.DiscountAdapter;
import com.small.commom.Action;
import com.small.commom.AsyncDataLoader;
import com.small.commom.HttpUtil;
import com.small.commom.Result;
import com.small.commom.Thinksns;
import com.small.commom.AsyncDataLoader.Callback;
import com.small.commom.Common;
import com.small.interfaces.Task;
import com.small.interfaces.Util;
import com.small.model.DiscountDetailModel;
import com.small.model.DiscountModel;
import com.small.model.DzModel;
import com.small.model.FavDiscountModel;
import com.small.model.SQChildModel;
import com.small.model.SQParentModel;
import com.small.model.ShopBaseInfoModel;
import com.small.model.ShopChildModel;
import com.small.model.ShopParentModel;
import com.small.view.LoadingDailog;
import com.small.view.custview.dialog.MyPopMenu;

/**
 * 优惠券信息
 * 
 * @author sunlibin
 * 
 */
public class DiscountHomeActivity extends Activity implements Task {

	ListView list_view;
	EditText txt_find;
	TextView tv_emepty;
	ImageButton btn_search, btn_back;
	LinearLayout layout_gps;
	Button btn_region, btn_type, btn_order;

	ArrayList<String> list_Shopfirst_name = null;
	ArrayList<String> list_Shopsecond_name = null;
	ArrayList<String> list_SQfirst_name = null;
	ArrayList<String> list_SQsecond_name = null;
	ArrayList<String> list_second_ordername = null;
	MyPopMenu pop;
	Context ctx;
	Action action;
	List<ShopParentModel> shoplist;
	List<SQParentModel> sqlist;
	List<ShopChildModel> childShopList;
	List<SQChildModel> childSQList;
	private final int SHOP_TYPE_FIRST = 0;
	private final int SHOP_TYPE_SECOND = 1;
	private final int SQ_TYPE_FIRST = 2;
	private final int SQ_TYPE_SECOND = 3;
	private final int ORDER_TAG = 4;

	private HashMap<String, Object> DiscountMap = null;
	private HashMap<String, Object> favDiscountMap = null;
	ArrayList<DiscountModel> discountList = null;
	DiscountAdapter list_adapter;
	private int result;

	
	private int orderType = 0;//为0 全部商圈+全部类型+默认顺序  
	private String districtID = "";
	private String businessDistrictID = ""; 
	private String shopFirstCateID = ""; 
	private String shopSecondCateID = "";  
 
	private int sq_child_position = 0;
	private int sq_parent_positon = 0; 
	private int shop_child_position = 0;
	private int shop_parent_positon = 0; 
	
	private int Tag = 0;//0 加载优惠信息，1加载详情 2收藏
	
	DiscountDetailModel discountModel = null;
	ArrayList<ShopBaseInfoModel> shopList = null;

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_discounthome_view);
		findView();
		initData();
	}

	private void initData() {
		Util.removeActivity();
		Util.addActivity(this);
		ctx = DiscountHomeActivity.this;
		action = new Action(ctx);
		Resources res = ctx.getResources();
		list_second_ordername = new ArrayList<String>();
		list_second_ordername.add(res.getString(R.string.nearest));
		list_second_ordername.add(res.getString(R.string.latest));
		list_second_ordername.add(res.getString(R.string.welcome)); 
		refreshData();
	}
	
	private void refreshData(){
		 
		action.showProgressDialog("正在加载...");
		new AsyncDataLoader(asyncCallback).execute();	
	}

	public void findView() {

		btn_region = (Button) this.findViewById(R.id.btn_filter_region);
		btn_type = (Button) this.findViewById(R.id.btn_filter_category);
		btn_order = (Button) this.findViewById(R.id.btn_filter_order);
		btn_order.setOnClickListener(onClick);
		btn_type.setOnClickListener(onClick);
		btn_region.setOnClickListener(onClick);
		btn_search = (ImageButton) this.findViewById(R.id.btn_search);
		btn_back = (ImageButton) this.findViewById(R.id.btn_home);
		btn_search.setOnClickListener(onClick);
		btn_back.setOnClickListener(onClick);

		tv_emepty = (TextView)this.findViewById(R.id.tv_empty);
		list_view = (ListView) this.findViewById(R.id.list_view);
		list_view.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long arg3) {
				
				gotoDetail(discountList.get(position).getCouponID());
				
			}
		});  
	}

	
	private void gotoDetail(final int i){
		action.showProgressDialog("正在加载详情数据...");
		new Thread(){
			public void run(){ 
				favDiscountMap = action.getDiscountDetail(String.valueOf(i));
				han.sendEmptyMessage(1);
			}
		}.start();
	}
	Handler han= new Handler(){

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) { 
			super.handleMessage(msg);
			action.stopProgressDialog();
			switch (msg.what) { 
			case 1: 
				if (favDiscountMap != null) { 
					discountModel = (DiscountDetailModel) favDiscountMap .get("discountModel");
					shopList = (ArrayList<ShopBaseInfoModel>) favDiscountMap .get("ShopList");
					if ( discountModel!=null ) {
						Intent intent = new Intent(DiscountHomeActivity.this,DiscountDetailActivity.class);
						Bundle mBundle = new Bundle();
						mBundle.putSerializable("discountModel", discountModel);
						mBundle.putSerializable("shopList", shopList);
						intent.putExtras(mBundle); 
						startActivity(intent); 
					} else{
						action.showShortToast("暂无优惠券详情，请稍后再试···");
					}
				} else {
					action.showShortToast("暂无优惠券详情，请稍后再试···");
				}
				 
				 
				break;
			}
		}
	};
	private Callback asyncCallback = new AsyncDataLoader.Callback() {

		@Override
		public void onStart() { 
		 
				DiscountMap = action.getDiscountInfo(districtID,businessDistrictID, String.valueOf(orderType),shopFirstCateID, shopSecondCateID, "", "86336301457058", 117.15863, 36.65231, 3, 1);				 
			 
 		}

		@Override
		public void onPrepare() {
		}

		@SuppressWarnings("unchecked")
		@Override
		public void onFinish() {

			action.stopProgressDialog();

			if (DiscountMap != null) {
				Integer i = (Integer) DiscountMap.get("result");
				result = (int) i;
				Log.d("				result", "" + result);
				discountList = (ArrayList<DiscountModel>) DiscountMap .get("discountList");

				resultMethod(result, discountList);
			} else {
				resultMethod(-2, null);
			}

		}
	};

	private void setEmpty(boolean t){
		if (t){
			tv_emepty.setVisibility(View.VISIBLE);
			list_view.setVisibility(View.GONE); 
		}else{
			tv_emepty.setVisibility(View.GONE);
			list_view.setVisibility(View.VISIBLE); 
		}
	}
	
	protected void resultMethod(int result2, List<DiscountModel> mydiscountlist) {
		setEmpty(true);
		switch (result2) {
		case 0: 
			action.showShortToast("请求失败，请稍候再试...");
			break;
		case 1:
			if (mydiscountlist != null) {
				setEmpty(false);
				list_adapter = new DiscountAdapter(DiscountHomeActivity.this, mydiscountlist);
				list_view.setAdapter(list_adapter);
			} else {
				action.showShortToast("请求失败，请稍候再试...");
			}
			break;
		case -2:
			action.showShortToast("数据异常，请求失败...");
			break;

		default:
			break;
		}
	}

	OnClickListener onClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.btn_home:
				finish();
				break;
			case R.id.btn_filter_region:
				regionDialog(btn_region);
				break;
			case R.id.btn_filter_category:
				filterCategory(btn_type);
				break;
			case R.id.btn_filter_order:
				filterOrder(btn_order); 
				break; 
			case R.id.btn_search:
				Thinksns.getInstance(DiscountHomeActivity.this).goToSearchDiscount();
				break; 
			}
		}
	};

	private void filterCategory(View view) {

		shoplist = action.getParentShopInfo();

		if (shoplist != null) {
			list_Shopfirst_name = new ArrayList<String>();
			for (ShopParentModel sqM : shoplist) {
				list_Shopfirst_name.add(sqM.getCategoryName());
			}
			list_Shopsecond_name = childShoplist(shoplist.get(shop_parent_positon)
					.getCategoryID());
			pop = new MyPopMenu(DiscountHomeActivity.this, list_Shopfirst_name,
					list_Shopsecond_name);
			pop.initPopupWindow(R.drawable.filter_mid_bg,
					R.layout.choice_single_listpop_layout, SHOP_TYPE_FIRST,
					SHOP_TYPE_SECOND);
			pop.show(view);
			pop.refresh(shop_parent_positon,shop_child_position , list_Shopsecond_name);
		}
		
	}

	protected void filterOrder(View view) {
		pop = new MyPopMenu(DiscountHomeActivity.this, null,
				list_second_ordername);
		pop.initPopupWindow(R.drawable.filter_right_bg,
				R.layout.choice_single_listpop_layout, -1, ORDER_TAG);
		pop.show(view);

	}

	private ArrayList<String> childShoplist(int id) {
		ArrayList<String> lists = null;
		childShopList = action.getChildShopInfo(id);
		if (childShopList != null) {
			lists = new ArrayList<String>();
			for (ShopChildModel sqCM : childShopList) {
				lists.add(sqCM.getCategoryName());
			}
		}
		return lists;
	}

	private void regionDialog(View view) {

		sqlist = action.getParentSQInfo();

		if (sqlist != null) {
			list_SQfirst_name = new ArrayList<String>();
			for (SQParentModel sqM : sqlist) {
				list_SQfirst_name.add(sqM.getCategoryName());
			}
			list_SQsecond_name = childSQlist(sqlist.get(sq_parent_positon).getCategoryID());
			pop = new MyPopMenu(DiscountHomeActivity.this, list_SQfirst_name,
					list_SQsecond_name);
			pop.initPopupWindow(R.drawable.filter_left_bg, R.layout.choice_single_listpop_layout, SQ_TYPE_FIRST, SQ_TYPE_SECOND);
			pop.show(view);
			pop.refresh(sq_parent_positon,sq_child_position , list_SQsecond_name);
		} 
	}

	private ArrayList<String> childSQlist(int id) {
		ArrayList<String> lists = null;
		childSQList = action.getChildSQInfo(id);
		if (childSQList != null) {
			lists = new ArrayList<String>();
			for (SQChildModel sqCM : childSQList) {
				lists.add(sqCM.getCategoryName());
			}
		}
		return lists;
	}
 

	// public void ShowFindJuli() {
	// final CharSequence[] items = { "500M", "1000M", "2000M", "3000M" };
	// AlertDialog dlg = new AlertDialog.Builder(DiscountHomeActivity.this)
	// .setTitle("请选择")
	// .setItems(items, new DialogInterface.OnClickListener() {
	// public void onClick(DialogInterface dialog, int item) {
	// switch (item) {
	// case 0:
	// intJuli = 500;
	// break;
	// case 1:
	// intJuli = 1000;
	// break;
	// case 2:
	// intJuli = 2000;
	// break;
	// case 3:
	// intJuli = 3000;
	// break;
	// }
	// btn_region.setText(items[item]);
	// // onData();
	// }
	// }).create();
	// dlg.show();
	// }

	@Override
	public void onRefresh(int page, HashMap<String, Object> map) {
		switch (page) {
		case SHOP_TYPE_FIRST:
			Integer i = (Integer) map.get("position");
			shop_parent_positon = i;
			list_Shopsecond_name = childShoplist(shoplist.get((int) i) .getCategoryID());
			pop.refresh(shop_parent_positon,shop_child_position , list_Shopsecond_name);
			shopSecondCateID = "";
			if (i!=0)  
				shopFirstCateID = String.valueOf(shoplist.get(i).getCategoryID());  
			break;
		case SHOP_TYPE_SECOND:
			Integer i2 = (Integer) map.get("position");
			shop_child_position = i2;
			Log.e("111", "您选择了第" + i2 + list_Shopsecond_name.get(i2));
			Toast.makeText(ctx, "您选择了第" + i2 + list_Shopsecond_name.get(i2), Toast.LENGTH_SHORT).show();
			pop.dismiss();
			if (i2!=0)  
				shopSecondCateID = String.valueOf(childShopList.get(i2).getCategoryID()); 
			 
			refreshData();
			btn_type.setText(list_Shopsecond_name.get(i2));
			break;
		case SQ_TYPE_FIRST:
			Integer i3 = (Integer) map.get("position");
			sq_parent_positon = i3;
			businessDistrictID = "";
			if (i3!=0)  
			districtID = String.valueOf(sqlist.get(i3).getCategoryID()); 	 
			list_SQsecond_name = childSQlist(sqlist.get(i3).getCategoryID());
			pop.refresh(sq_parent_positon,sq_child_position , list_SQsecond_name);
			break;
		case SQ_TYPE_SECOND:
			Integer i4 = (Integer) map.get("position"); 
			sq_child_position  = i4;
			Toast.makeText(ctx, "您选择了第" + i4 + list_SQsecond_name.get(i4),Toast.LENGTH_SHORT).show();
			if (i4!=0) {
				businessDistrictID = String.valueOf(childSQList.get(i4).getCategoryID()); 
			} 
			pop.dismiss();
			refreshData();
			btn_region.setText(list_SQsecond_name.get(i4));
			break;
		case ORDER_TAG:
			Integer i5 = (Integer) map.get("position"); 
			Toast.makeText(ctx, "您选择了第" + i5 + list_second_ordername.get(i5), Toast.LENGTH_SHORT).show();
			btn_order.setText(list_second_ordername.get(i5));
			orderType = i5;
			refreshData();
			pop.dismiss();
			break;
		}
	}

	@Override
	protected void onDestroy() {
		if (Common.dbtool != null) {
			Common.dbtool.close();
			Common.dbtool = null;
		}
		super.onDestroy();
	}
}
